import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import type {
  Config,
  DatabaseConfig,
  JwtConfig,
  UploadConfig,
} from './config.interface';

@Injectable()
export class AppConfigService {
  constructor(private configService: ConfigService) {}

  get nodeEnv(): 'development' | 'production' | 'test' {
    return this.configService.getOrThrow<Config['app']['nodeEnv']>(
      'app.nodeEnv',
    );
  }

  get port(): number {
    return this.configService.getOrThrow<number>('app.port');
  }

  get databaseConfig(): DatabaseConfig {
    return {
      host: this.configService.getOrThrow<string>('database.host'),
      port: this.configService.getOrThrow<number>('database.port'),
      username: this.configService.getOrThrow<string>('database.username'),
      password: this.configService.getOrThrow<string>('database.password'),
      database: this.configService.getOrThrow<string>('database.database'),
    };
  }

  get jwtConfig(): JwtConfig {
    return {
      secret: this.configService.getOrThrow<string>('jwt.secret'),
      expiresIn: this.configService.getOrThrow<string>('jwt.expiresIn'),
    };
  }

  get uploadConfig(): UploadConfig {
    return {
      path: this.configService.getOrThrow<string>('upload.path'),
      maxSize: this.configService.getOrThrow<number>('upload.maxSize'),
    };
  }

  get isProduction(): boolean {
    return this.nodeEnv === 'production';
  }

  get isDevelopment(): boolean {
    return this.nodeEnv === 'development';
  }

  get isTest(): boolean {
    return this.nodeEnv === 'test';
  }

  // 添加数据库连接字符串获取方法
  get databaseUrl(): string {
    const config = this.databaseConfig;
    return `mysql://${config.username}:${config.password}@${config.host}:${config.port}/${config.database}`;
  }

  // 添加上传路径相关方法
  get uploadDir(): string {
    return this.configService.getOrThrow<string>('upload.path');
  }

  get tempUploadDir(): string {
    return `${this.uploadDir}/temp`;
  }

  // 添加配置验证方法
  validateConfig(): void {
    const requiredConfigs = [
      'app.nodeEnv',
      'app.port',
      'database.host',
      'database.port',
      'database.username',
      'database.password',
      'database.database',
      'jwt.secret',
    ];

    for (const config of requiredConfigs) {
      if (!this.configService.get(config)) {
        throw new Error(`Missing required config: ${config}`);
      }
    }
  }

  // 添加配置获取的安全方法
  getConfig<T = any>(key: string, defaultValue?: T): T {
    const value = this.configService.get<T>(key, defaultValue);
    if (value === undefined && defaultValue === undefined) {
      throw new Error(`Config key not found: ${key}`);
    }
    return value as T;
  }

  // 添加文件系统相关配置
  get filesystemConfig() {
    return {
      maxFileSize: this.uploadConfig.maxSize,
      tempDir: this.tempUploadDir,
      uploadDir: this.uploadDir,
      allowedMimeTypes: ['image/jpeg', 'image/png', 'image/gif', 'application/pdf'],
    };
  }

  // 添加安全相关配置
  get securityConfig() {
    return {
      bcryptSaltRounds: 10,
      passwordMinLength: 8,
      passwordMaxLength: 32,
      maxLoginAttempts: 5,
      lockoutDuration: 15 * 60 * 1000, // 15分钟
    };
  }

  // 添加缓存相关配置
  get cacheConfig() {
    return {
      ttl: 300, // 5分钟
      max: 100, // 最大缓存项数
    };
  }

  // 添加初始化方法
  async init() {
    try {
      this.validateConfig();
      await this.ensureUploadDirs();
    } catch (error) {
      throw new Error(`配置初始化失败: ${error.message}`);
    }
  }

  // 确保上传目录存在
  private async ensureUploadDirs() {
    const fs = await import('fs/promises');
    const dirs = [this.uploadDir, this.tempUploadDir];
    
    for (const dir of dirs) {
      try {
        await fs.access(dir);
      } catch {
        await fs.mkdir(dir, { recursive: true });
      }
    }
  }

  // 添加日志配置
  get logConfig() {
    return {
      level: this.isDevelopment ? 'debug' : 'info',
      logDir: './logs',
      maxFiles: 30,
      maxSize: '10m',
      format: this.isDevelopment ? 'dev' : 'combined',
    };
  }

  // 添加监控配置
  get monitorConfig() {
    return {
      enabled: this.isProduction,
      interval: 60000, // 1分钟
      metrics: {
        cpu: true,
        memory: true,
        disk: true,
      },
    };
  }

  // 添加错误处理配置
  get errorConfig() {
    return {
      stackTrace: !this.isProduction,
      logErrors: true,
      errorLogFile: `${this.logConfig.logDir}/error.log`,
      sensitiveFields: ['password', 'token', 'secret'],
    };
  }

  // 添加性能配置
  get performanceConfig() {
    return {
      compression: true,
      responseTimeout: 30000, // 30秒
      bodyLimit: '50mb',
      rateLimit: {
        windowMs: 15 * 60 * 1000, // 15分钟
        max: this.isProduction ? 100 : 1000, // 根据环境设置不同的限制
      },
    };
  }

  // 添加配置重载方法
  async reloadConfig() {
    try {
      await this.configService.get('config');
      await this.init();
      return true;
    } catch (error) {
      throw new Error(`配置重载失败: ${error.message}`);
    }
  }

  // 添加 CORS 配置
  get corsConfig() {
    return {
      enabled: true,
      origin: this.isDevelopment ? '*' : process.env.ALLOWED_ORIGINS?.split(',') || [],
      methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
      allowedHeaders: ['Content-Type', 'Authorization'],
      credentials: true,
      maxAge: 3600,
    };
  }

  // 添加 API 相关配置
  get apiConfig() {
    return {
      prefix: '/api',
      version: 'v1',
      docs: {
        enabled: !this.isProduction,
        title: 'ASAP CMS API',
        description: 'ASAP CMS API Documentation',
        version: '1.0.0',
        path: '/docs',
      },
      pagination: {
        defaultLimit: 10,
        maxLimit: 100,
      },
    };
  }

  // 添加静态资源配置
  get staticConfig() {
    return {
      prefix: '/static',
      rootPath: this.uploadDir,
      serveStatic: !this.isProduction,
      cacheControl: this.isProduction ? 'public, max-age=31536000' : 'no-cache',
      dotfiles: 'deny',
      etag: true,
    };
  }

  // 添加会话配置
  get sessionConfig() {
    return {
      secret: this.jwtConfig.secret,
      name: 'asap.sid',
      resave: false,
      saveUninitialized: false,
      cookie: {
        httpOnly: true,
        secure: this.isProduction,
        maxAge: 24 * 60 * 60 * 1000, // 1天
      },
    };
  }

  // 添加数据库连接池配置
  get databasePoolConfig() {
    return {
      min: this.isDevelopment ? 1 : 5,
      max: this.isDevelopment ? 5 : 20,
      idle: 10000,
      acquire: 30000,
      evict: 1000,
      autostart: true,
    };
  }

  // 添加请求超时配置
  get timeoutConfig() {
    return {
      http: 30000,      // HTTP 请求超时
      db: 10000,        // 数据库查询超时
      upload: 300000,   // 文件上传超时
      download: 300000, // 文件下载超时
    };
  }

  // 添加请求大小限制配置
  get requestLimitConfig() {
    return {
      json: '2mb',
      urlencoded: '2mb',
      multipart: '50mb',
      raw: '5mb',
      text: '2mb',
    };
  }

  // 添加清理任务配置
  get cleanupConfig() {
    return {
      tempFiles: {
        enabled: true,
        interval: 3600000,  // 1小时
        maxAge: 86400000,   // 1天
      },
      logs: {
        enabled: true,
        interval: 86400000, // 1天
        maxAge: 2592000000, // 30天
      },
    };
  }
}
